package org.dreamwork.tools.sherpa.ncnn.examples;

import com.k2fsa.sherpa.ncnn.SherpaNcnn;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DecodeFileTest {
    public static void main (String[] args) throws IOException {
        Path path = Paths.get (args [0]);
        if (Files.notExists (path)) {
            System.err.println (path + " not exists.");
            System.exit (-1);
            return;
        }

        System.out.println ("recognizing file " + path + " ...");

        try (InputStream in = Files.newInputStream (path);
             SherpaNcnn sherpa = SherpaHelper.initRecognizer (6)) {
            long skip = in.skip (44);
            System.out.println ("skipped " + skip + " bytes.");
            final int N = 6400;
            byte[]  raw     = new byte[N];
            float[] samples = new float[N/2];
            long start = System.currentTimeMillis ();
            while (in.read (raw, 0, N) > 0) {
                for (int i = 0; i < N; i += 2) {
                    short value = (short) (((raw[i + 1] & 0xff) << 8) | (raw[i] & 0xff));
                    samples[i / 2] = value / 32768.0f;
                }
                sherpa.acceptSamples (samples);
                while (sherpa.isReady ()) {
                    sherpa.decode ();
                }
            }
            // Send a blank packet so that the sherpa-ncnn engine
            // can correctly identify the endpoint
            float[] tail = new float[4800];
            sherpa.acceptSamples (tail);
            sherpa.inputFinished ();
            while (sherpa.isReady ()) {
                sherpa.decode ();
            }
            String text = sherpa.getText ();
            if (text!= null && !text.isEmpty ()) {
                System.out.println (text);
            }
            System.out.printf ("takes %d ms.%n", System.currentTimeMillis () - start);
        }
    }
}
